<template>
  <div class="employee-management">
    <!-- 侧边栏 -->
    <div class="sidebar">
      <div class="sidebar-header">
        <div class="admin-logo">
          <div class="admin-logo-icon">管</div>
          <div class="admin-logo-text">管理系统</div>
        </div>
      </div>
      
      <div class="sidebar-menu">
        <div 
          v-for="menu in menuList" 
          :key="menu.name"
          class="menu-item"
          :class="{ active: menu.name === 'employee' }"
          @click="handleMenuClick(menu)"
        >
          <div class="menu-icon">{{ menu.icon }}</div>
          <span>{{ menu.label }}</span>
        </div>
      </div>
      
      <div class="sidebar-footer">
        <div class="admin-avatar-container">
          <div class="admin-avatar">{{ adminInitial }}</div>
          <div class="admin-info">
            <div class="admin-name">{{ adminName }}</div>
            <div class="admin-role">超级管理员</div>
          </div>
        </div>
        
        <!-- 退出登录按钮 -->
        <div class="logout-btn" @click="handleLogout">
          <div class="logout-icon">🚪</div>
          <span>退出登录</span>
        </div>
      </div>
    </div>
    
    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 顶部导航 -->
      <div class="top-nav">
        <h1 class="page-title">
          <div class="page-title-icon">👥</div>
          员工账号管理
        </h1>
        
        <div class="top-actions">
          <el-button class="action-btn export-btn" @click="handleExport">
            <span class="btn-icon">📊</span>
            导出数据
          </el-button>
          <el-button class="action-btn import-btn" @click="handleImport">
            <span class="btn-icon">📥</span>
            批量导入
          </el-button>
          <el-button class="action-btn primary-btn" @click="handleAdd">
            <span class="btn-icon">➕</span>
            添加员工
          </el-button>
        </div>
      </div>
      
      <!-- 筛选区域 -->
      <div class="filter-section">
        <el-form :model="queryForm" :inline="true">
          <el-form-item label="员工姓名/工号">
            <el-input 
              v-model="queryForm.keyword" 
              placeholder="请输入员工姓名或工号"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="所属部门">
            <el-select 
              v-model="queryForm.department" 
              placeholder="全部部门"
              clearable
              style="width: 180px"
            >
              <el-option label="全部部门" value=""></el-option>
              <el-option 
                v-for="dept in departmentList" 
                :key="dept" 
                :label="dept" 
                :value="dept"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="账号状态">
            <el-select 
              v-model="queryForm.status" 
              placeholder="全部状态"
              clearable
              style="width: 180px"
            >
              <el-option label="全部状态" value=""></el-option>
              <el-option label="已启用" :value="1"></el-option>
              <el-option label="已禁用" :value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button class="filter-btn reset-btn" @click="handleReset">
              <span class="btn-icon">🔄</span>
              重置
            </el-button>
            <el-button class="filter-btn search-btn" @click="handleQuery">
              <span class="btn-icon">🔍</span>
              查询
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 批量操作区域 -->
      <div class="batch-section">
        <div class="batch-left">
          <el-checkbox 
            v-model="selectAll" 
            @change="handleSelectAllChange"
          >
            全选
          </el-checkbox>
          <div class="batch-actions">
            <el-button class="batch-btn enable-btn" size="small" @click="handleBatchEnable">
              <span class="btn-icon">✅</span>
              批量启用
            </el-button>
            <el-button class="batch-btn disable-btn" size="small" @click="handleBatchDisable">
              <span class="btn-icon">⛔</span>
              批量禁用
            </el-button>
            <el-button class="batch-btn delete-btn" size="small" @click="handleBatchDelete">
              <span class="btn-icon">🗑️</span>
              批量删除
            </el-button>
          </div>
        </div>
        <div class="total-text">共 {{ total }} 个员工账号</div>
      </div>
      
      <!-- 数据表格区域 -->
      <div class="table-section">
        <el-table
          :data="employeeList"
          v-loading="loading"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="员工信息" min-width="180">
            <template #default="{ row }">
              <div class="account-info">
                <div class="account-avatar">{{ row.realName ? row.realName.charAt(0) : 'U' }}</div>
                <div class="account-details">
                  <div class="account-name">{{ row.realName }}</div>
                  <div class="account-id">{{ row.employeeNo }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="department" label="部门" width="120" />
          <el-table-column prop="position" label="职位" width="120" />
          <el-table-column label="账号角色" width="120">
            <template #default="{ row }">
              <el-tag 
                v-for="role in row.roles" 
                :key="role.id"
                :type="role.roleCode === 'ROLE_ADMIN' ? 'danger' : 'primary'"
                size="small"
              >
                {{ role.roleName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="账号状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'info'" size="small">
                {{ row.status === 1 ? '已启用' : '已禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="最后登录" width="160">
            <template #default="{ row }">
              {{ row.lastLoginTime ? formatDateTime(row.lastLoginTime) : '从未登录' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="260" fixed="right">
            <template #default="{ row }">
              <el-button class="table-action-btn edit-btn" link size="small" @click="handleEdit(row)">
                <span class="btn-icon">✏️</span>
                编辑
              </el-button>
              <el-button class="table-action-btn reset-pwd-btn" link size="small" @click="handleResetPassword(row)">
                <span class="btn-icon">🔑</span>
                重置密码
              </el-button>
              <el-button 
                class="table-action-btn"
                :class="row.status === 1 ? 'disable-status-btn' : 'enable-status-btn'"
                link 
                size="small" 
                @click="handleToggleStatus(row)"
              >
                <span class="btn-icon">{{ row.status === 1 ? '⛔' : '✅' }}</span>
                {{ row.status === 1 ? '禁用' : '启用' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="queryForm.current"
            v-model:page-size="queryForm.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 新增/编辑员工对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      @close="handleDialogClose"
    >
      <el-form 
        ref="employeeFormRef"
        :model="employeeForm" 
        :rules="employeeRules" 
        label-width="80px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="employeeForm.username" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="员工工号" prop="employeeNo">
              <el-input v-model="employeeForm.employeeNo" placeholder="不填写将自动生成" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="employeeForm.realName" placeholder="请输入真实姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属部门" prop="department">
              <el-input v-model="employeeForm.department" placeholder="请输入所属部门" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职位" prop="position">
              <el-input v-model="employeeForm.position" placeholder="请输入职位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="employeeForm.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="employeeForm.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="!employeeForm.id">
            <el-form-item label="密码" prop="password">
              <el-input 
                v-model="employeeForm.password" 
                type="password" 
                placeholder="不填写将使用默认密码123456" 
                show-password
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="24">
            <el-form-item label="账号角色" prop="roleIds">
              <el-select 
                v-model="employeeForm.roleIds" 
                multiple 
                placeholder="请选择角色"
                style="width: 100%"
              >
                <el-option 
                  v-for="role in roleList" 
                  :key="role.id" 
                  :label="role.roleName" 
                  :value="role.id"
                >
                  <span style="float: left">{{ role.roleName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ role.roleCode }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="24">
            <el-form-item label="账号状态" prop="status">
              <el-radio-group v-model="employeeForm.status">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button class="dialog-btn cancel-btn" @click="dialogVisible = false">
          <span class="btn-icon">❌</span>
          取消
        </el-button>
        <el-button class="dialog-btn confirm-btn" @click="handleSubmit">
          <span class="btn-icon">✔️</span>
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 导入员工对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="批量导入员工"
      width="600px"
      @close="handleImportDialogClose"
    >
      <div class="import-content">
        <div class="import-tips">
          <el-alert
            title="重要提示"
            type="warning"
            :closable="false"
          >
            <template #default>
              <p style="margin: 0;">• 导入的员工默认密码为 <strong>123456</strong></p>
              <p style="margin: 5px 0 0 0;">• 请先下载Excel模板，按照模板格式填写员工信息</p>
              <p style="margin: 5px 0 0 0;">• 工号、用户名、真实姓名为必填项</p>
              <p style="margin: 5px 0 0 0;">• 支持的格式：.xls 和 .xlsx</p>
            </template>
          </el-alert>
        </div>

        <div class="template-download">
          <el-button class="download-btn" @click="handleDownloadTemplate">
            <span class="btn-icon">📥</span>
            下载Excel模板
          </el-button>
        </div>

        <div class="file-upload">
          <el-upload
            class="upload-demo"
            :auto-upload="false"
            :on-change="handleFileChange"
            :limit="1"
            accept=".xls,.xlsx"
            :file-list="importFile ? [importFile] : []"
          >
            <template #trigger>
              <el-button class="upload-btn" size="large">
                <span class="btn-icon">📁</span>
                选择Excel文件
              </el-button>
            </template>
          </el-upload>
        </div>
      </div>

      <template #footer>
        <el-button class="dialog-btn cancel-btn" @click="importDialogVisible = false">
          <span class="btn-icon">❌</span>
          取消
        </el-button>
        <el-button class="dialog-btn confirm-btn" @click="handleConfirmImport" :loading="importLoading">
          <span class="btn-icon">✔️</span>
          开始导入
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import { getAllRoles } from '@/api/role'

const router = useRouter()
const userStore = useUserStore()

// 管理员信息
const adminName = computed(() => userStore.userInfo?.realName || '系统管理员')
const adminInitial = computed(() => adminName.value.charAt(0))

// 菜单列表
const menuList = [
  { name: 'dashboard', label: '数据看板', icon: '📊', path: '/admin/dashboard' },
  { name: 'employee', label: '员工管理', icon: '👥', path: '/admin/employee' },
  { name: 'card', label: '福利卡管理', icon: '🎁', path: '/admin/welfare-card' },
  { name: 'product', label: '商品管理', icon: '🛒', path: '/admin/product' },
  { name: 'order', label: '订单管理', icon: '📦', path: '/admin/order' },
  { name: 'statistics', label: '数据统计', icon: '📈', path: '/admin/statistics' }
]

// 查询表单
const queryForm = reactive({
  keyword: '',
  department: '',
  status: '',
  current: 1,
  size: 10
})

// 员工列表数据
const employeeList = ref([])
const total = ref(0)
const loading = ref(false)
const selectAll = ref(false)
const selectedIds = ref([])
const departmentList = ref([])
const roleList = ref([])

// 导入对话框
const importDialogVisible = ref(false)
const importLoading = ref(false)
const importFile = ref(null)

// 对话框
const dialogVisible = ref(false)
const dialogTitle = computed(() => employeeForm.id ? '编辑员工' : '新增员工')
const employeeFormRef = ref()
const employeeForm = reactive({
  id: null,
  username: '',
  employeeNo: '',
  realName: '',
  department: '',
  position: '',
  phone: '',
  email: '',
  password: '',
  accountBalance: 0,
  status: 1,
  roleIds: []
})

const employeeRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
  phone: [{ pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }],
  email: [{ type: 'email', message: '邮箱格式不正确', trigger: 'blur' }]
}

// 菜单点击
const handleMenuClick = (menu) => {
  if (menu.path) {
    router.push(menu.path)
  }
}

// 查询员工列表
const getEmployeeList = async () => {
  loading.value = true
  try {
    const params = {
      ...queryForm,
      status: queryForm.status === '' ? null : queryForm.status
    }
    const response = await request.get('/employees/page', { params })
    
    if (response.success) {
      employeeList.value = response.data.records
      total.value = response.data.total
    }
  } catch (error) {
    console.error('查询员工列表失败:', error)
    ElMessage.error('查询失败')
  } finally {
    loading.value = false
  }
}

// 查询部门列表
const getDepartmentList = async () => {
  try {
    const response = await request.get('/employees/departments')
    if (response.success) {
      departmentList.value = response.data
    }
  } catch (error) {
    console.error('获取部门列表失败:', error)
  }
}

// 查询角色列表
const getRoleList = async () => {
  try {
    console.log('开始获取角色列表...')
    const response = await getAllRoles()
    if (response.success) {
      roleList.value = response.data
      console.log('角色列表获取成功:', response.data)
    } else {
      console.error('获取角色列表失败:', response.message)
      ElMessage.error('获取角色列表失败')
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  }
}

// 查询
const handleQuery = () => {
  queryForm.current = 1
  getEmployeeList()
}

// 重置
const handleReset = () => {
  queryForm.keyword = ''
  queryForm.department = ''
  queryForm.status = ''
  queryForm.current = 1
  getEmployeeList()
}

// 页码改变
const handleCurrentChange = (page) => {
  queryForm.current = page
  getEmployeeList()
}

// 每页数量改变
const handleSizeChange = (size) => {
  queryForm.size = size
  queryForm.current = 1 // 改变每页数量时重置到第一页
  getEmployeeList()
}

// 全选
const handleSelectAllChange = (val) => {
  // TODO: 实现全选逻辑
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 添加员工
const handleAdd = async () => {
  console.log('点击添加员工，当前角色列表长度:', roleList.value.length)
  
  // 确保角色列表已加载
  if (roleList.value.length === 0) {
    console.log('角色列表为空，开始加载...')
    await getRoleList()
  }
  
  Object.keys(employeeForm).forEach(key => {
    if (key === 'status') {
      employeeForm[key] = 1
    } else if (key === 'roleIds') {
      employeeForm[key] = []
    } else if (key === 'accountBalance') {
      employeeForm[key] = 0
    } else {
      employeeForm[key] = null
    }
  })
  
  console.log('打开新增员工对话框，角色列表:', roleList.value)
  dialogVisible.value = true
}

// 编辑员工
const handleEdit = async (row) => {
  console.log('点击编辑员工，当前角色列表长度:', roleList.value.length)
  
  // 确保角色列表已加载
  if (roleList.value.length === 0) {
    console.log('角色列表为空，开始加载...')
    await getRoleList()
  }
  
  // 获取员工详情（包含角色信息）
  try {
    console.log('获取员工详情，员工ID:', row.id)
    const response = await request.get(`/employees/${row.id}`)
    if (response.success) {
      const employee = response.data
      console.log('员工详情获取成功:', employee)
      
      Object.keys(employeeForm).forEach(key => {
        if (key === 'roleIds') {
          // 将角色列表转换为角色ID数组
          employeeForm[key] = employee.roles ? employee.roles.map(r => r.id) : []
          console.log('员工角色ID数组:', employeeForm[key])
        } else {
          employeeForm[key] = employee[key]
        }
      })
      
      console.log('打开编辑员工对话框，角色列表:', roleList.value)
      dialogVisible.value = true
    }
  } catch (error) {
    console.error('获取员工详情失败:', error)
    ElMessage.error('获取员工信息失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await employeeFormRef.value.validate()
    
    const url = employeeForm.id ? `/employees/${employeeForm.id}` : '/employees'
    const method = employeeForm.id ? 'put' : 'post'
    
    const response = await request[method](url, employeeForm)
    
    if (response.success) {
      ElMessage.success(employeeForm.id ? '更新成功' : '添加成功')
      dialogVisible.value = false
      getEmployeeList()
    }
  } catch (error) {
    console.error('提交失败:', error)
  }
}

// 关闭对话框
const handleDialogClose = () => {
  employeeFormRef.value?.resetFields()
}

// 重置密码
const handleResetPassword = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要重置 ${row.realName} 的密码吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await request.put(`/employees/${row.id}/reset-password`)
    
    if (response.success) {
      ElMessage.success(response.message)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('重置密码失败:', error)
    }
  }
}

// 切换状态
const handleToggleStatus = async (row) => {
  const action = row.status === 1 ? 'disable' : 'enable'
  const text = row.status === 1 ? '禁用' : '启用'
  
  try {
    await ElMessageBox.confirm(`确定要${text} ${row.realName} 的账号吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await request.put(`/employees/${row.id}/${action}`)
    
    if (response.success) {
      ElMessage.success(`${text}成功`)
      getEmployeeList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error(`${text}失败:`, error)
    }
  }
}

// 批量启用
const handleBatchEnable = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要启用的员工')
    return
  }
  
  try {
    const response = await request.put('/employees/batch/enable', selectedIds.value)
    
    if (response.success) {
      ElMessage.success('批量启用成功')
      getEmployeeList()
    }
  } catch (error) {
    console.error('批量启用失败:', error)
  }
}

// 批量禁用
const handleBatchDisable = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要禁用的员工')
    return
  }
  
  try {
    const response = await request.put('/employees/batch/disable', selectedIds.value)
    
    if (response.success) {
      ElMessage.success('批量禁用成功')
      getEmployeeList()
    }
  } catch (error) {
    console.error('批量禁用失败:', error)
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要删除的员工')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedIds.value.length} 个员工吗？此操作不可恢复！`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await request.delete('/employees/batch', { data: selectedIds.value })
    
    if (response.success) {
      ElMessage.success('批量删除成功')
      getEmployeeList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
    }
  }
}

// 导出数据
const handleExport = async () => {
  try {
    // 构建导出参数
    const params = {
      keyword: queryForm.keyword || '',
      department: queryForm.department || '',
      status: queryForm.status !== '' ? queryForm.status : null
    }
    
    // 使用axios下载文件
    const { data } = await request.get('/employees/export', {
      params,
      responseType: 'blob'
    })
    
    // 创建blob对象
    const blob = new Blob([data], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    })
    
    // 创建下载链接
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    
    // 生成文件名（带时间戳）
    const date = new Date()
    const timestamp = `${date.getFullYear()}${(date.getMonth() + 1).toString().padStart(2, '0')}${date.getDate().toString().padStart(2, '0')}_${date.getHours().toString().padStart(2, '0')}${date.getMinutes().toString().padStart(2, '0')}${date.getSeconds().toString().padStart(2, '0')}`
    link.download = `员工数据导出_${timestamp}.xlsx`
    
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败：' + (error.message || '未知错误'))
  }
}

// 批量导入
const handleImport = () => {
  importDialogVisible.value = true
}

// 下载模板
const handleDownloadTemplate = async () => {
  try {
    // 使用axios下载，responseType设置为blob
    const { data } = await request.get('/employees/download-template', {
      responseType: 'blob'
    })
    
    // 创建blob对象
    const blob = new Blob([data], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    })
    
    // 创建下载链接
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = 'employee_template.xlsx'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('模板下载成功')
  } catch (error) {
    console.error('下载模板失败:', error)
    ElMessage.error('下载模板失败')
  }
}

// 文件选择变化
const handleFileChange = (file) => {
  importFile.value = file.raw
  return false // 阻止自动上传
}

// 确认导入
const handleConfirmImport = async () => {
  if (!importFile.value) {
    ElMessage.warning('请选择要导入的Excel文件')
    return
  }
  
  const formData = new FormData()
  formData.append('file', importFile.value)
  
  importLoading.value = true
  try {
    const response = await request.post('/employees/import', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    if (response.success) {
      const result = response.data
      let message = `导入完成：成功${result.successCount}条，失败${result.failCount}条`
      
      if (result.failDetails && result.failDetails.length > 0) {
        const failReasons = result.failDetails.map(item => 
          `第${item.rowNum}行: ${item.reason}`
        ).join('\n')
        message += '\n失败详情：\n' + failReasons
      }
      
      ElMessage.success(message)
      importDialogVisible.value = false
      getEmployeeList()
    }
  } catch (error) {
    console.error('导入失败:', error)
    ElMessage.error('导入失败：' + (error.message || '未知错误'))
  } finally {
    importLoading.value = false
  }
}

// 关闭导入对话框
const handleImportDialogClose = () => {
  importFile.value = null
}

// 退出登录
const handleLogout = async () => {
  try {
    await userStore.logout()
    ElMessage.success('已退出登录')
    router.push('/login')
  } catch (error) {
    console.error('退出登录失败:', error)
    ElMessage.error('退出登录失败')
  }
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', { 
    year: 'numeric', 
    month: '2-digit', 
    day: '2-digit', 
    hour: '2-digit', 
    minute: '2-digit' 
  })
}

// 初始化
onMounted(() => {
  getEmployeeList()
  getDepartmentList()
  getRoleList()
})
</script>

<style lang="scss" scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.employee-management {
  display: flex;
  min-height: 100vh;
  background-color: #f5f7fa;
}

/* 侧边栏样式 */
.sidebar {
  width: 220px;
  background-color: white;
  height: 100vh;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
  position: fixed;
  left: 0;
  top: 0;
  z-index: 100;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.admin-logo {
  display: flex;
  align-items: center;
}

.admin-logo-icon {
  width: 36px;
  height: 36px;
  background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%);
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 10px;
  color: white;
  font-weight: bold;
  font-size: 18px;
}

.admin-logo-text {
  font-size: 18px;
  font-weight: 600;
  color: #f56c6c;
}

.sidebar-menu {
  flex: 1;
  padding: 20px 0;
  overflow-y: auto;
}

.menu-item {
  padding: 12px 20px;
  cursor: pointer;
  display: flex;
  align-items: center;
  transition: all 0.3s;
  
  &:hover {
    background-color: #f5f7fa;
  }
  
  &.active {
    background-color: #fef0f0;
    color: #f56c6c;
    border-right: 3px solid #f56c6c;
  }
}

.menu-icon {
  margin-right: 10px;
  width: 20px;
  text-align: center;
}

.sidebar-footer {
  padding: 15px 20px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.admin-avatar-container {
  display: flex;
  align-items: center;
  width: 100%;
}

.admin-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #f56c6c;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  font-weight: bold;
  margin-right: 10px;
}

.admin-info {
  flex: 1;
}

.admin-name {
  font-weight: 500;
  font-size: 14px;
}

.admin-role {
  color: #909399;
  font-size: 12px;
}

/* 退出登录按钮 */
.logout-btn {
  width: 100%;
  background: linear-gradient(135deg, #ef5350 0%, #e53935 100%);
  color: white;
  padding: 8px 12px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(239, 83, 80, 0.3);
}

.logout-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(239, 83, 80, 0.4);
}

.logout-icon {
  font-size: 14px;
}

/* 主内容区域 */
.main-content {
  flex: 1;
  margin-left: 220px;
  padding: 20px;
}

/* 顶部导航 */
.top-nav {
  background-color: white;
  border-radius: 12px;
  padding: 15px 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  font-size: 22px;
  font-weight: 600;
  display: flex;
  align-items: center;
  margin: 0;
}

.page-title-icon {
  width: 32px;
  height: 32px;
  background-color: #f56c6c;
  border-radius: 6px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 10px;
  color: white;
}

.top-actions {
  display: flex;
  gap: 10px;
}

.filter-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  
  :deep(.el-form) {
    .el-form-item {
      margin-bottom: 16px;
      
      &:last-child {
        margin-bottom: 0;
      }
    }
    
    .el-form-item__label {
      font-weight: 600;
      font-size: 14px;
      color: #606266;
    }
    
    .el-input__wrapper,
    .el-select .el-input__wrapper {
      border-radius: 8px;
      padding: 6px 12px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
      
      &:hover {
        box-shadow: 0 2px 6px rgba(64, 158, 255, 0.15);
      }
      
      &.is-focus {
        box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
      }
    }
  }
}

.batch-section {
  background: white;
  border-radius: 12px;
  padding: 15px 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.batch-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.batch-actions {
  display: flex;
  gap: 10px;
}

.total-text {
  color: #606266;
  font-size: 14px;
}

.table-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.account-info {
  display: flex;
  align-items: center;
}

.account-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #409EFF;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  font-weight: bold;
  margin-right: 10px;
}

.account-details {
  display: flex;
  flex-direction: column;
}

.account-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.account-id {
  color: #909399;
  font-size: 12px;
}

.pagination-section {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

/* ========================================
   按钮美化 - 暖色调主题
   ======================================== */

/* 顶部操作按钮 */
.action-btn {
  border-radius: 8px;
  padding: 10px 20px;
  font-weight: 500;
  transition: all 0.3s ease;
  border: none;
  display: inline-flex;
  align-items: center;
  gap: 6px;
  
  .btn-icon {
    font-size: 16px;
  }
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }
  
  &:active {
    transform: translateY(0);
  }
}

.export-btn {
  background: linear-gradient(135deg, #ffa726 0%, #fb8c00 100%);
  color: white;
  
  &:hover {
    background: linear-gradient(135deg, #fb8c00 0%, #f57c00 100%);
  }
}

.import-btn {
  background: linear-gradient(135deg, #66bb6a 0%, #43a047 100%);
  color: white;
  
  &:hover {
    background: linear-gradient(135deg, #43a047 0%, #388e3c 100%);
  }
}

.primary-btn {
  background: linear-gradient(135deg, #ff7043 0%, #ff5722 100%);
  color: white;
  
  &:hover {
    background: linear-gradient(135deg, #ff5722 0%, #f4511e 100%);
  }
}

/* 筛选按钮 */
.filter-btn {
  border-radius: 6px;
  padding: 8px 16px;
  font-weight: 500;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  gap: 4px;
  
  .btn-icon {
    font-size: 14px;
  }
}

.reset-btn {
  background: linear-gradient(135deg, #bdbdbd 0%, #9e9e9e 100%);
  color: white;
  border: none;
  
  &:hover {
    background: linear-gradient(135deg, #9e9e9e 0%, #757575 100%);
    transform: translateY(-1px);
  }
}

.search-btn {
  background: linear-gradient(135deg, #42a5f5 0%, #1e88e5 100%);
  color: white;
  border: none;
  
  &:hover {
    background: linear-gradient(135deg, #1e88e5 0%, #1976d2 100%);
    transform: translateY(-1px);
  }
}

/* 批量操作按钮 */
.batch-btn {
  border-radius: 6px;
  padding: 6px 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  border: none;
  display: inline-flex;
  align-items: center;
  gap: 4px;
  
  .btn-icon {
    font-size: 14px;
  }
  
  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 3px 8px rgba(0, 0, 0, 0.15);
  }
}

.enable-btn {
  background: linear-gradient(135deg, #66bb6a 0%, #43a047 100%);
  color: white;
  
  &:hover {
    background: linear-gradient(135deg, #43a047 0%, #388e3c 100%);
  }
}

.disable-btn {
  background: linear-gradient(135deg, #ffa726 0%, #fb8c00 100%);
  color: white;
  
  &:hover {
    background: linear-gradient(135deg, #fb8c00 0%, #f57c00 100%);
  }
}

.delete-btn {
  background: linear-gradient(135deg, #ef5350 0%, #e53935 100%);
  color: white;
  
  &:hover {
    background: linear-gradient(135deg, #e53935 0%, #d32f2f 100%);
  }
}

/* 表格操作按钮 */
.table-action-btn {
  font-weight: 500;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.2s ease;
  display: inline-flex;
  align-items: center;
  gap: 3px;
  
  .btn-icon {
    font-size: 14px;
  }
  
  &:hover {
    transform: scale(1.05);
  }
}

.edit-btn {
  color: #42a5f5;
  
  &:hover {
    color: #1e88e5;
    background-color: #e3f2fd;
  }
}

.reset-pwd-btn {
  color: #ffa726;
  
  &:hover {
    color: #fb8c00;
    background-color: #fff3e0;
  }
}

.enable-status-btn {
  color: #66bb6a;
  
  &:hover {
    color: #43a047;
    background-color: #e8f5e9;
  }
}

.disable-status-btn {
  color: #ef5350;
  
  &:hover {
    color: #e53935;
    background-color: #ffebee;
  }
}

/* 对话框按钮 */
.dialog-btn {
  border-radius: 6px;
  padding: 10px 24px;
  font-weight: 500;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  gap: 6px;
  
  .btn-icon {
    font-size: 14px;
  }
  
  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 3px 8px rgba(0, 0, 0, 0.15);
  }
}

.cancel-btn {
  background: linear-gradient(135deg, #bdbdbd 0%, #9e9e9e 100%);
  color: white;
  border: none;
  
  &:hover {
    background: linear-gradient(135deg, #9e9e9e 0%, #757575 100%);
  }
}

.confirm-btn {
  background: linear-gradient(135deg, #ff7043 0%, #ff5722 100%);
  color: white;
  border: none;
  
  &:hover {
    background: linear-gradient(135deg, #ff5722 0%, #f4511e 100%);
  }
}

/* 页面标题图标优化 - 暖色调 */
.page-title-icon {
  background: linear-gradient(135deg, #ff7043 0%, #ff5722 100%);
  box-shadow: 0 2px 8px rgba(255, 112, 67, 0.3);
}

/* Logo 图标优化 - 暖色调 */
.admin-logo-icon {
  background: linear-gradient(135deg, #ff7043 0%, #ff5722 100%);
  box-shadow: 0 2px 6px rgba(255, 112, 67, 0.3);
}

.admin-logo-text {
  color: #ff5722;
}

/* 侧边栏菜单激活状态 - 暖色调 */
.menu-item.active {
  background: linear-gradient(90deg, rgba(255, 112, 67, 0.08) 0%, rgba(255, 112, 67, 0.15) 100%);
  color: #ff5722;
  border-right: 3px solid #ff5722;
}

/* 管理员头像 - 暖色调 */
.admin-avatar {
  background: linear-gradient(135deg, #ff7043 0%, #ff5722 100%);
  box-shadow: 0 2px 6px rgba(255, 112, 67, 0.3);
}

/* 表格样式优化 */
:deep(.el-table) {
  .el-table__header th {
    background-color: #fff5f2;
    color: #ff5722;
    font-weight: 600;
  }
  
  .el-table__row:hover {
    background-color: #fff9f7;
  }
}

/* 标签优化 - 暖色调 */
:deep(.el-tag) {
  border-radius: 12px;
  padding: 0 10px;
  font-weight: 500;
  
  &.el-tag--success {
    background: linear-gradient(135deg, #66bb6a 0%, #43a047 100%);
    border: none;
    color: white;
  }
  
  &.el-tag--info {
    background: linear-gradient(135deg, #bdbdbd 0%, #9e9e9e 100%);
    border: none;
    color: white;
  }
  
  &.el-tag--danger {
    background: linear-gradient(135deg, #ff7043 0%, #ff5722 100%);
    border: none;
    color: white;
  }
  
  &.el-tag--primary {
    background: linear-gradient(135deg, #42a5f5 0%, #1e88e5 100%);
    border: none;
    color: white;
  }
}

/* 对话框优化 */
:deep(.el-dialog) {
  border-radius: 12px;
  overflow: hidden;
  
  .el-dialog__header {
    background: linear-gradient(135deg, #ff7043 0%, #ff5722 100%);
    padding: 20px;
    
    .el-dialog__title {
      color: white;
      font-weight: 600;
      font-size: 18px;
    }
    
    .el-dialog__headerbtn .el-dialog__close {
      color: white;
      font-size: 20px;
      
      &:hover {
        color: #fff;
      }
    }
  }
  
  .el-dialog__body {
    padding: 25px 30px;
  }
}

/* 表单优化 */
:deep(.el-form) {
  .el-row {
    margin-bottom: 0;
  }
  
  .el-form-item {
    margin-bottom: 24px;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .el-form-item__label {
    color: #ff5722;
    font-weight: 600;
    font-size: 14px;
    margin-bottom: 8px;
  }
  
  .el-input__wrapper {
    border-radius: 8px;
    padding: 8px 15px;
    transition: all 0.3s ease;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
    
    &:hover {
      box-shadow: 0 2px 6px rgba(255, 112, 67, 0.15);
    }
    
    &.is-focus {
      box-shadow: 0 0 0 2px rgba(255, 112, 67, 0.2);
    }
  }
  
  .el-select {
    width: 100%;
    
    .el-input__wrapper {
      border-radius: 8px;
      padding: 8px 15px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
      
      &:hover {
        box-shadow: 0 2px 6px rgba(255, 112, 67, 0.15);
      }
      
      &.is-focus {
        box-shadow: 0 0 0 2px rgba(255, 112, 67, 0.2);
      }
    }
  }
  
  .el-radio-group {
    .el-radio {
      margin-right: 16px;
      margin-bottom: 8px;
    }
  }
}

/* 分页优化 */
:deep(.el-pagination) {
  .el-pager li.is-active {
    background: linear-gradient(135deg, #ff7043 0%, #ff5722 100%);
    color: white;
  }
  
  .el-pager li:hover {
    color: #ff5722;
  }
  
  button:hover {
    color: #ff5722;
  }
}

/* 员工信息头像 - 暖色调 */
.account-avatar {
  background: linear-gradient(135deg, #ff7043 0%, #ff5722 100%);
  box-shadow: 0 2px 4px rgba(255, 112, 67, 0.3);
}

/* 导入对话框样式 */
.import-content {
  padding: 20px 0;
}

.import-tips {
  margin-bottom: 20px;
}

.template-download {
  text-align: center;
  margin-bottom: 20px;
}

.download-btn {
  background: linear-gradient(135deg, #42a5f5 0%, #1e88e5 100%);
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  gap: 6px;
  
  .btn-icon {
    font-size: 16px;
  }
  
  &:hover {
    background: linear-gradient(135deg, #1e88e5 0%, #1976d2 100%);
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(30, 136, 229, 0.3);
  }
}

.file-upload {
  text-align: center;
  
  .upload-btn {
    background: linear-gradient(135deg, #66bb6a 0%, #43a047 100%);
    color: white;
    border: none;
    padding: 12px 24px;
    border-radius: 8px;
    font-weight: 500;
    transition: all 0.3s ease;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    
    .btn-icon {
      font-size: 16px;
    }
    
    &:hover {
      background: linear-gradient(135deg, #43a047 0%, #388e3c 100%);
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(67, 160, 71, 0.3);
    }
  }
}

/* 响应式优化 */
@media (max-width: 768px) {
  .action-btn,
  .filter-btn,
  .batch-btn,
  .dialog-btn {
    padding: 8px 16px;
    font-size: 13px;
    
    .btn-icon {
      font-size: 13px;
    }
  }
  
  .table-action-btn {
    padding: 3px 6px;
    font-size: 12px;
    
    .btn-icon {
      font-size: 12px;
    }
  }
  
  /* 对话框在小屏幕上调整宽度 */
  :deep(.el-dialog) {
    width: 95% !important;
    margin: 0 auto;
    
    .el-dialog__body {
      padding: 20px 15px;
    }
  }
  
  /* 表单在小屏幕上变为单列 */
  :deep(.el-form) {
    .el-col {
      max-width: 100%;
      flex: 0 0 100%;
    }
  }
}
</style>

